<?php

namespace App\Models;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'password','nickname'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function roles(){
        return $this->belongsToMany('App\Models\Role', 'user_roles', 'user_id', 'role_id');
    }

    public function hasPermission(){
        if(!\Auth::user()){
            return [];
        }
        else{
            $roleModel = app(\App\Models\Role::class)->query();

            $roles = \Auth::user()->roles;

            $roleIds = [];

            foreach($roles as $role){
                array_push($roleIds,$role->id);
            }

            $roles = $roleModel->whereIn('id',$roleIds)->with('permissions')->get();

            $permissions = [];

            foreach ($roles as $role) {
                foreach ($role->permissions as $permission) {
                    array_push($permissions, $permission->toArray());
                }
                
            }

            // dd($permissions);

            return $permissions;
        }

    }
}
